import { useMemberStore } from "@/stores/modules/menber";
const baseURL = "http://192.168.100.183";
const SERVERPORT = 9000;
const SERVERPATH = baseURL + ":" + SERVERPORT;

const httpInterceptor = {
  invoke(options: UniApp.RequestOptions) {
    if (!options.url.startsWith("http")) {
      options.url = SERVERPATH + options.url;
    }
    options.timeout = 5000;
    // 添加小程序端請求表示頭
    options.header = {
      ...options.header,
      "content-type": "miniapp",
    };
    const memberStore = useMemberStore();
    const token = memberStore.profile?.token;
    if (token) {
      options.header.Authorization = token;
    }
  },
};
uni.addInterceptor("request", httpInterceptor);
uni.addInterceptor("uploadFile", httpInterceptor);

interface Data<T> {
  code: number;
  message: string;
  result: T;
}
export const http = <T>(options: UniApp.RequestOptions) => {
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data as Data<T>);
        } else if (res.statusCode === 401) {
          const memberStore = useMemberStore();
          memberStore.clearProfile();
          uni.reLaunch({
            url: "/pages/login/login",
          });
          reject(res);
        } else {
          uni.showToast({
            title: (res.data as Data<T>).message,
            icon: "none",
          });
          reject(res);
        }
      },
      fail: (err) => {
        uni.showToast({
          title: "网络错误",
          icon: "none",
        });
        reject(err);
      },
    });
  });
};
